# get the server side payloay from facebook access

# get the facebook host and referer for the http requests.
require "00_common"


INPUT_DIR   = "./facebook_payload/"
OUTPUT_DIR  = "./facebook_payload_svr/"

module FacebookPayloadSvr
  def self.get_all_files
  	Common.get_all_files(INPUT_DIR)
  end

  def self.handle_each_line(line)
  	fields = line.split "|"
    # new_line = "#{local_time_stamp}|#{session_id}|#{session_start_time}|#{server_ip}|#{server_port}|#{client_ip}|#{client_port}"
    # new_line = new_line + "|#{referer}|#{host}|#{content_type}|#{content_length}|#{user_agent}|#{connection}|#{c_request}|#{s_response}"
    local_time_stamp  = fields[0]
    referer           = fields[7]
    host              = fields[8]
    c_request         = fields[13]
    s_response        = fields[14]


    if referer.include? "facebook" or referer.include? "fbcdn" or host.include? "facebook" or host.include? "fbcdn"
      new_line = "#{local_time_stamp}|#{referer}|#{host}|#{c_request}|#{s_response}"
    else
      nil
    end
  end

  def self.handle_each_file(file_name)
  	puts "now handling : " + file_name
    file = File.open INPUT_DIR + file_name, "r"
    output_file_name = Common.alternate_file_name(file_name, "_raw_", "_svr_")
    output_file = File.open output_file_name, "w"

    begin
      counter = 0
      while line = file.readline
        new_line = handle_each_line(line)
        if new_line
          output_file.puts new_line
        end
      end
    rescue Exception => e
      puts e.to_s
      file.close
    end

    output_file.close
  end

  def self.handle_all_files(all_files)
  	all_files.each do |file_name|
    	if Common.file_exist?(OUTPUT_DIR, Common.alternate_file_name(file_name, "_raw_", "_svr_"))
    	  puts "exist file:" + file_name
    	else
        handle_each_file(file_name)
        Common.move_file Common.alternate_file_name(file_name, "_raw_", "_svr_"), OUTPUT_DIR
    	end
    end
  end
end


begin
  all_files = FacebookPayloadSvr.get_all_files
  FacebookPayloadSvr.handle_all_files all_files
rescue Exception => e
	puts e.to_s
end